package com.example.myapp.Fragment;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.myapp.ADO.Chatlist_Adapter;
import com.example.myapp.ADO.FriendAapter;
import com.example.myapp.ADO.MsgList_Aapter;
import com.example.myapp.ADO.SQLDAO;
import com.example.myapp.Listviewloading.MyFooterAdapter;
import com.example.myapp.Listviewloading.MyHeaderAdapter;
import com.example.myapp.Loading.ShapeLoadingDialog;
import com.example.myapp.Model.Msg;
import com.example.myapp.Model.MsgList;
import com.example.myapp.Model.User;
import com.example.myapp.R;
import com.sak.ultilviewlib.UltimateRefreshView;
import com.sak.ultilviewlib.interfaces.OnHeaderRefreshListener;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

//import android.support.v4.app.Fragment;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ContactFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ContactFragment extends Fragment {
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_SHOW_TEXT = "text";
    private String mContentText;

    private ShapeLoadingDialog shapeLoadingDialog;



    private Timer timer;
    private UltimateRefreshView mUltimateRefreshView;
    private RecyclerView recyclerView;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
    private String updatatime="";
    private Chatlist_Adapter adapter;
    private  String  url ="http://pybchat.justwen233.cn/findMsglist";//查找聊天记录列表
    private List<MsgList> msgList = new ArrayList<>();

    private RequestQueue requestQueue;

    private RequestQueue requestQueue2;
    public ContactFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @return A new instance of fragment HomeFragment.
     */
    public static ContactFragment newInstance(String param1) {
        ContactFragment fragment = new ContactFragment();
        Bundle args = new Bundle();
        args.putString(ARG_SHOW_TEXT, param1);
        fragment.setArguments(args);
        return fragment;
    }
    //开启异步线程
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0: {
                    queryALLMsgs();
                    break;
                }
            }
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mContentText = getArguments().getString(ARG_SHOW_TEXT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_contact, container, false);

        mUltimateRefreshView = (UltimateRefreshView)rootView.findViewById(R.id.refreshView);
        recyclerView= rootView.findViewById(R.id.recyclerView);

         requestQueue = Volley.newRequestQueue(getActivity());
         requestQueue2 = Volley.newRequestQueue(getActivity());
        /**部下拉刷新*/
        mUltimateRefreshView.setBaseHeaderAdapter(new MyHeaderAdapter(getActivity()));
        mUltimateRefreshView.setBaseFooterAdapter(new MyFooterAdapter(getActivity()));
        /**头部下拉刷新事件*/
        mUltimateRefreshView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh(UltimateRefreshView view) {
                RefreshMsg();
//                Map<String,String> map=new HashMap<String,String>();
//                map.put("author", BmobUser.getCurrentUser(User.class).getObjectId());
//                JSONObject params=new JSONObject(map);
//                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, params, new com.android.volley.Response.Listener<JSONObject>() {
//                    @Override
//                    public void onResponse(JSONObject response) {
//                        try {
//                            JSONArray jsonArray= response.getJSONArray("result");
//                            if(jsonArray.length()>msgList.size()){
//                                msgList=JSONArrayToArrayMsgList(jsonArray);
//                                adapter=new Chatlist_Adapter( getActivity(),msgList);
//                                recyclerView.setAdapter(adapter);
//                            }
//                            Log.w("vivi", "onResponse: "+ response);
//                        }catch (Exception e ){
//                            Log.w("vivi", "error: " + e.getMessage());
//
//                        }
//
//                    }
//                }, new Response.ErrorListener() {
//                    @Override
//                    public void onErrorResponse(VolleyError error) {
//                        error.printStackTrace();
//                        Log.d("vivi", "error: " + error.getMessage());
//                    }
//                });
//
//                //添加队列
//                requestQueue2.add(jsonObjectRequest);
//                requestQueue2.cancelAll(this);
                mUltimateRefreshView.onHeaderRefreshComplete();
            }
        });


        Message message = new Message();
        message.what = 0;
        handler.sendMessage(message);

        return rootView;
    }



    /** 获取聊天列表*/
    private  void queryALLMsgs(){
        if (!BmobUser.isLogin()) {
            Log.w("aaaa", "登陆后在操作" );
            return;
        }
        Map<String,String> map=new HashMap<String,String>();
        map.put("author", BmobUser.getCurrentUser(User.class).getObjectId());
        JSONObject params=new JSONObject(map);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, params, new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray= response.getJSONArray("result");
                    msgList=JSONArrayToArrayMsgList(jsonArray);
                    Log.w("viai", "onResponse: "+ msgList.size());
                    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());//正常listview
                    recyclerView.setLayoutManager(layoutManager);
                    recyclerView.setItemViewCacheSize(500);
                    adapter=new Chatlist_Adapter(getActivity(),msgList);
                    recyclerView.setAdapter(adapter);
                    Log.w("vivi", "onResponse: "+ response);

                    // TODO 设置定时器
                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            RefreshMsg();

                        }
                    }, 1000, 2000);  // TODO 每隔一秒执行一下

                }catch (Exception e ){
                    Log.w("vivi", "error: " + e.getMessage());
//                    Toast.makeText(getActivity(),"错误"+e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("vivi", "error: " + error.getMessage());
            }
        });

        //添加队列
        requestQueue.add(jsonObjectRequest);
        requestQueue.cancelAll(this);

    }

    private  void RefreshMsg(){
        if (!BmobUser.isLogin()) {
            Log.w("aaaa", "登陆后在操作" );
            return;
        }
        Map<String,String> map=new HashMap<String,String>();
        map.put("author", BmobUser.getCurrentUser(User.class).getObjectId());
        JSONObject params=new JSONObject(map);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, params, new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray= response.getJSONArray("result");
                    msgList=JSONArrayToArrayMsgList(jsonArray);
                    Log.w("viai", "onResponse: "+ msgList.size());
                    LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());//正常listview
                    recyclerView.setLayoutManager(layoutManager);
                    recyclerView.setItemViewCacheSize(500);
                    adapter=new Chatlist_Adapter(getActivity(),msgList);
                    recyclerView.setAdapter(adapter);
                    Log.w("vivi", "onResponse: "+ response);

                }catch (Exception e ){
                    Log.w("vivi", "error: " + e.getMessage());
//                    Toast.makeText(getActivity(),"错误"+e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("vivi", "error: " + error.getMessage());
            }
        });

        //添加队列
        requestQueue.add(jsonObjectRequest);
        requestQueue.cancelAll(this);
    }

    private  List<MsgList> JSONArrayToArrayMsgList(JSONArray jsonArray){
        List<MsgList> msgList=new ArrayList<>();
        try {
            for (int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject  = jsonArray.getJSONObject(i);
                MsgList msg=new MsgList();
               msg.setUserid(jsonObject.getString("userid"));
                msg.setUsername(jsonObject.getString("username"));
                msg.setIcon(jsonObject.getString("icon"));
                msg.setNum(jsonObject.getInt("num"));
                msg.setMsg(jsonObject.getString("msg"));
                msgList.add(msg);
            }
        }catch (Exception e ){
            Log.w("viai", "onResponse: "+ e);
        }



        return msgList;
    }







    //关闭的时候
    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer!=null){
            timer.cancel();
        }
    }




    private  void openLoading(){
        shapeLoadingDialog = new ShapeLoadingDialog.Builder(getActivity())
                .loadText("加载中...")
                .build();
        shapeLoadingDialog.show();
    }
    //关闭网络加载
    private  void closeLoading(){
        shapeLoadingDialog.dismiss();
    }
}
